import { Page, View, Document, Text, Image } from "@react-pdf/renderer";
import { StyleSheet } from '@react-pdf/renderer';
import { useState, useEffect } from 'react';
import {Resume} from "../../../lib/redux/types";
import {Settings} from "../../../lib/redux/settingsSlice";
import {ResumePDFImage} from "../ResumePDF/common/ResumePDFImage";

// 单位转换常数
const mmToPt = (mm: number) => mm * 2.83465;
const pxToPt = (px: number) => px * 0.75;

// 增强的样式解析器const numericProps = ['fontsize', 'lineheight', 'width', 'height'];
// 修正后的样式解析器
const parseHTMLStyles = (styleString: string) => {
    const styleObj: Record<string, string | number> = {};
    const declarations = styleString.split(';').filter(Boolean);

    declarations.forEach(decl => {
        let [prop, value] = decl.split(':').map(s => s.trim());
        if (!prop || !value) return;

        // 修正属性名转换（支持驼峰命名）
        prop = prop.replace(/-([a-z])/gi, (_, c) => c.toUpperCase());

        // 增强数值解析
        const numMatch = value.match(/[-+]?\d*\.?\d+/);
        const numValue = numMatch ? parseFloat(numMatch[0]) : NaN;

        const numProps = ['fontsize', 'lineheight', 'width', 'height','margintop','marginbottom','padding'];

        if (numProps.includes(prop.toLowerCase()) && !isNaN(numValue)) {
            if (value.includes('mm')) {
                styleObj[prop] = mmToPt(numValue);
            } else if (value.includes('px')) {
                styleObj[prop] = pxToPt(numValue);
            } else {
                styleObj[prop] = numValue;
            }
        } else {
            styleObj[prop] = value;
        }

        // 特别处理display属性
        if (prop === 'display' && value === 'block') {
            styleObj.width = '100%';
        }
    });

    return styleObj;
};

// 改进的HTML转换器
const convertHTMLToMetadata = (rawHTML: string) => {
    const doc = new DOMParser().parseFromString(rawHTML, "text/html");
    const body = doc.body;

    const walk = (node: Element): any => {
        const tag = node.tagName.toLowerCase();
        const styles = parseHTMLStyles(node.getAttribute('style') || '');
        const children = Array.from(node.children as HTMLCollectionOf<Element>).map(walk);

        // 处理文本元素
        if (tag === 'text') {
            return {
                type: 'text',
                content: node.textContent?.trim()+'\n' || '',
                styles: {
                    fontSize: Number(styles.fontSize) || 12,  // 123改为12
                    fontWeight: styles.fontWeight || 'normal',
                    color: styles.color || '#000',
                    lineHeight: Number(styles.lineHeight) || undefined, // 移除默认值
                    marginTop: Number(styles.marginTop) || 0,  // 新增
                    marginBottom: Number(styles.marginBottom) || 0,
                    whiteSpace: 'pre',  // 改回pre保持换行
                    width: '100%',
                }
            };
        }

        // 处理图片元素
        if (tag === 'img') {
            return {
                type: 'image',
                src: node.getAttribute('src') || '',
                styles: {
                    width: Number(styles.width) || 100,
                    height: Number(styles.height) || 100
                }
            };
        }

        // 容器处理
        return {
            type: tag,
            styles: {
                ...styles,
                flexDirection: styles.display === 'grid' ? 'row' : 'column',
                gap: Number(styles.gap) || 0,
                padding: Number(styles.padding) || 0
            },
            children
        };
    };

    return {
        pageStyles: parseHTMLStyles(body.getAttribute('style') || ''),
        content: walk(body)
    };
};

// 类型安全的渲染器（修正版）
/*const ElementRenderer = ({ node, isPDF }: { node: any; isPDF: boolean }) => {
    // 增强的样式转换器
    const convertStyles = (styles: any) => {
        const baseStyles = {
            fontSize: Number(styles?.fontSize) || 12, // 123改回合理值12
            lineHeight: styles?.lineHeight ? Number(styles.lineHeight) : undefined,
            marginTop: Number(styles?.marginTop) || 0,
            marginBottom: Number(styles?.marginBottom) || 0,
        };

        // PDF模式需要特殊处理布局属性
        return isPDF
            ? {
                ...styles,
                ...baseStyles,
                display: 'flex', // react-pdf强制flex布局
                flexDirection: styles?.flexDirection || 'column'
            }
            : {
                ...styles,
                ...baseStyles,
                display: 'block', // 浏览器使用标准流
                // 转换特殊属性名
                marginTop: `${baseStyles.marginTop}pt`,
                marginBottom: `${baseStyles.marginBottom}pt`
            };
    };

    if (!node) return null;

    // 严格模式分支
    if (!isPDF) {
        // 浏览器模式使用原生HTML元素
        switch (node.type) {
            case 'text':
                return (
                    <span style={convertStyles(node.styles)}>
            {node.content}
          </span>
                );
            case 'image':
                return (
                    <img
                        src={node.src}
                        style={convertStyles(node.styles)}
                        alt="content-image"
                    />
                );
            default:
                return (
                    <div style={convertStyles(node.styles)}>
                        {node.children?.map((child: any, index: number) => (
                            <ElementRenderer
                                key={index}
                                node={child}
                                isPDF={isPDF}  // 透传模式参数
                            />
                        ))}
                    </div>
                );
        }
    }

    // PDF模式使用react-pdf组件
    switch (node.type) {
        case 'text':
            return <Text style={convertStyles(node.styles)}>{node.content}</Text>;
        case 'image':
            return <Image src={node.src} style={convertStyles(node.styles)} />;
        default:
            return (
                <View style={convertStyles(node.styles)}>
                    {node.children?.map((child: any, index: number) => (
                        <ElementRenderer
                            key={index}
                            node={child}
                            isPDF={isPDF}  // 确保透传到子组件
                        />
                    ))}
                </View>
            );
    }
};*/

// 类型安全的渲染器
const ElementRenderer = ({ node, isPDF}: { node: any ,isPDF:boolean}) => {
    const convertStyles = (styles: any) => ({
        ...styles,
        fontSize: Number(styles.fontSize) || 12, // 123改12
        lineHeight: styles.lineHeight ? Number(styles.lineHeight) : undefined,
        marginTop: Number(styles.marginTop) || 0,  // 新增
        marginBottom: Number(styles.marginBottom) || 0,
    });

    if (!node) return null;

    switch (node.type) {
        case 'text':
            return <Text style={convertStyles(node.styles)}>{node.content}</Text>;
        case 'image':
            return isPDF ? (
                <Image src={node.src} style={convertStyles(node.styles)} />
            ) : (
                <img src={node.src} style={convertStyles(node.styles)} />
            );
        default:
            return (
                <View style={convertStyles(node.styles)}>
                    {node.children?.map((child: any, index: number) => (
                        <ElementRenderer key={index} node={child} />
                    ))}
                </View>
            );
    }
};

// 主组件
export const Poster = ({
                           resume,
                           settings,
                           isPDF = false,
                       }: {
    resume: Resume;
    settings: Settings;
    isPDF?: boolean;
}) => {
    const background = settings.background;
    const BG_IMAGE_PATH = background.url || "/images/default-bg.jpg";
    const [rawHTML, setRawHTML] = useState("");
    const [metadata, setMetadata] = useState<any>(null);

    useEffect(() => {
        fetch('/sample1.txt')
            .then(r => r.text())
            .then(text => {
                setRawHTML(text);
                setMetadata(convertHTMLToMetadata(text)); // 异步更新状态
            });
    }, []);
    console.log("metadata: ",metadata)

    if (!metadata) return null;

    return (
        <Document>
            <Page
                size="A4"
                style={{
                    display: 'flex',
                    justifyContent: 'center',    // 垂直居中
                    alignItems: 'center',        // 水平居中
                    backgroundColor: metadata.pageStyles.background,
                    fontFamily: metadata.pageStyles.fontFamily
                }}
            >
                <ResumePDFImage
                    isPDF={isPDF}
                    src={BG_IMAGE_PATH} // 使用环境变量
                    style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        opacity: background.opacity,
                        zIndex: 0,
                        objectFit: 'cover'
                    }}
                />
                <ElementRenderer node={metadata.content} isPDF={isPDF}/>
            </Page>
        </Document>
    );
};
// 基础样式表
const styles = StyleSheet.create({
    page: {
        flexDirection: 'column',
        backgroundColor: '#FFF'
    },
    section: {
        margin: 10,
        padding: 10,
        flexGrow: 1
    }
});